# -*- coding: utf-8 -*-
__author__ = 'gerry'

import numpy as np
import matplotlib.pyplot as plt
import math
import datetime
from mpl_toolkits.mplot3d import Axes3D

# ufunc函数
# ufunc韩式是一种能对数组的每个元素进行运算的函数,Numpy内置的很多ufunc都是用C语言实现的

x1 = np.linspace(0,2*np.pi,10)
y = np.sin(x1)
plt.rcParams['lines.color']='r'
plt.plot(x1,y)

# plt.show()

print "====================================================="

x = [i*0.001 for i in xrange(1000000)]
def sin_math(x):
    for i,t in enumerate(x):
        x[i] = math.sin(t)

def sin_numpy(x):
    np.sin(x,x)

def sin_numpy_loop(x):
    for i,t in enumerate(x):
        x[i]=np.sin(t)

xl = x[:]
starttime = datetime.datetime.now()
sin_math(xl)
endtime = datetime.datetime.now()
print(endtime-starttime).seconds

xa = np.array(x)
starttime1 = datetime.datetime.now()
sin_numpy(xa)
endtime1 = datetime.datetime.now()
print(endtime1-starttime1).seconds


xj = x[:]
starttime2 = datetime.datetime.now()
sin_numpy_loop(xj)
endtime2 = datetime.datetime.now()
print(endtime2-starttime2).seconds
print "====================================================="
# 2.2.1四则运算
# Numpy提供了许多ufunc函数，例如计算两个数组之和的add()函数
a = np.arange(0,4)
b = np.arange(1,5)

print a
print np.add(a,b)
np.multiply(a,b,a)
print a

#数组的运算符以及对应的ufunc函数
#y = x1+x2:add(x1,x2,y)
#y = x1-x2:subtract(x1,x2,y)
#y = x1*x2:myltiply(x1,x2,y)
#y = x1/x2:divide(x1,x2,y),如果两个数组的元素为整数，那么用整除除法
#y = x1/x2:true_divide(x1,x2,y),总是返回精确的值
#y = x1//x2:add(x1,x2,y)，总是对返回值取整
#y = -x:negative(x,y)
#y = x1**x2:power(x1,x2,y)
#y = x1%x2:mod(x1,x2,y)


print "====================================================="
#2.2.2比较运算符合布尔运算
result = np.array([1,2,3])<np.array([3,2,1])
print result

#比较运算符和相应的ufunc函数
#y = x1==x2:equal(x1,x2,y)
#y = x1!=x2:not_equal(x1,x2,y)
#y = x1<x2:less(x1,x2,y)
#y = x1<=x2:less_equal(x1,x2,y)
#y = x1>x2:greater(x1,x2,y)
#y = x1>=x2:greater_equal(x1,x2,y)

# 由于Python中的布尔运算符and、or和not等关键字，无法被重载，因此数组的布尔运算符有只能通过ufunc函数运行
# np.logical_and(),np.logical_not(),np.logical_or()

a1 = np.arange(5)
b1 = np.arange(4,-1,-1)
print a1>b1
print np.logical_or(a1==b1,a1>b1) #和a1>=b1相同

print np.any(a1==b1)


print "====================================================="
# 2.2.4广播
# 当使用ufunc函数对两个数组进行计算时，ufunc函数会对这两个数组的对应元素进行计算
# 因此它要求这两个数组的形状相同，如果形状不同，会进行如下广播（broadcasting）处理
a2 = np.arange(0,60,10).reshape(-1,1)
b2 = np.arange(0,5)
c = a2+b2
print c

fig = plt.figure()
ax = Axes3D(fig)
x,y = np.ogrid[-2:2:20j,-2:2:20j]
z = x*np.exp(-x**2-y**2)
ax.plot_surface(x,y,z)
plt.show()








